Merge "Mention translatewiki.net on edits only, when edit a default message"
[lhc/web/wiklou.git] / includes / api / ApiQueryBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 7, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * This is a base class for all Query modules.
29 * It provides some common functionality such as constructing various SQL
30 * queries.
31 *
32 * @ingroup API
33 */
34 abstract class ApiQueryBase extends ApiBase {
35
36 private $mQueryModule, $mDb, $tables, $where, $fields, $options, $join_conds;
37
38 /**
39 * @param ApiQuery $queryModule
40 * @param string $moduleName
41 * @param string $paramPrefix
42 */
43 public function __construct( ApiQuery $queryModule, $moduleName, $paramPrefix = '' ) {
44 parent::__construct( $queryModule->getMain(), $moduleName, $paramPrefix );
45 $this->mQueryModule = $queryModule;
46 $this->mDb = null;
47 $this->resetQueryParams();
48 }
49
50 /************************************************************************//**
51 * @name Methods to implement
52 * @{
53 */
54
55 /**
56 * Get the cache mode for the data generated by this module. Override
57 * this in the module subclass. For possible return values and other
58 * details about cache modes, see ApiMain::setCacheMode()
59 *
60 * Public caching will only be allowed if *all* the modules that supply
61 * data for a given request return a cache mode of public.
62 *
63 * @param array $params
64 * @return string
65 */
66 public function getCacheMode( $params ) {
67 return 'private';
68 }
69
70 /**
71 * Override this method to request extra fields from the pageSet
72 * using $pageSet->requestField('fieldName')
73 * @param ApiPageSet $pageSet
74 */
75 public function requestExtraData( $pageSet ) {
76 }
77
78 /**@}*/
79
80 /************************************************************************//**
81 * @name Data access
82 * @{
83 */
84
85 /**
86 * Get the main Query module
87 * @return ApiQuery
88 */
89 public function getQuery() {
90 return $this->mQueryModule;
91 }
92
93 /**
94 * @see ApiBase::getParent()
95 */
96 public function getParent() {
97 return $this->getQuery();
98 }
99
100 /**
101 * Get the Query database connection (read-only)
102 * @return DatabaseBase
103 */
104 protected function getDB() {
105 if ( is_null( $this->mDb ) ) {
106 $this->mDb = $this->getQuery()->getDB();
107 }
108
109 return $this->mDb;
110 }
111
112 /**
113 * Selects the query database connection with the given name.
114 * See ApiQuery::getNamedDB() for more information
115 * @param string $name Name to assign to the database connection
116 * @param int $db One of the DB_* constants
117 * @param array $groups Query groups
118 * @return DatabaseBase
119 */
120 public function selectNamedDB( $name, $db, $groups ) {
121 $this->mDb = $this->getQuery()->getNamedDB( $name, $db, $groups );
122 }
123
124 /**
125 * Get the PageSet object to work on
126 * @return ApiPageSet
127 */
128 protected function getPageSet() {
129 return $this->getQuery()->getPageSet();
130 }
131
132 /**@}*/
133
134 /************************************************************************//**
135 * @name Querying
136 * @{
137 */
138
139 /**
140 * Blank the internal arrays with query parameters
141 */
142 protected function resetQueryParams() {
143 $this->tables = array();
144 $this->where = array();
145 $this->fields = array();
146 $this->options = array();
147 $this->join_conds = array();
148 }
149
150 /**
151 * Add a set of tables to the internal array
152 * @param string|string[] $tables Table name or array of table names
153 * @param string|null $alias Table alias, or null for no alias. Cannot be
154 * used with multiple tables
155 */
156 protected function addTables( $tables, $alias = null ) {
157 if ( is_array( $tables ) ) {
158 if ( !is_null( $alias ) ) {
159 ApiBase::dieDebug( __METHOD__, 'Multiple table aliases not supported' );
160 }
161 $this->tables = array_merge( $this->tables, $tables );
162 } else {
163 if ( !is_null( $alias ) ) {
164 $this->tables[$alias] = $tables;
165 } else {
166 $this->tables[] = $tables;
167 }
168 }
169 }
170
171 /**
172 * Add a set of JOIN conditions to the internal array
173 *
174 * JOIN conditions are formatted as array( tablename => array(jointype,
175 * conditions) e.g. array('page' => array('LEFT JOIN',
176 * 'page_id=rev_page')) . conditions may be a string or an
177 * addWhere()-style array
178 * @param array $join_conds JOIN conditions
179 */
180 protected function addJoinConds( $join_conds ) {
181 if ( !is_array( $join_conds ) ) {
182 ApiBase::dieDebug( __METHOD__, 'Join conditions have to be arrays' );
183 }
184 $this->join_conds = array_merge( $this->join_conds, $join_conds );
185 }
186
187 /**
188 * Add a set of fields to select to the internal array
189 * @param array|string $value Field name or array of field names
190 */
191 protected function addFields( $value ) {
192 if ( is_array( $value ) ) {
193 $this->fields = array_merge( $this->fields, $value );
194 } else {
195 $this->fields[] = $value;
196 }
197 }
198
199 /**
200 * Same as addFields(), but add the fields only if a condition is met
201 * @param array|string $value See addFields()
202 * @param bool $condition If false, do nothing
203 * @return bool $condition
204 */
205 protected function addFieldsIf( $value, $condition ) {
206 if ( $condition ) {
207 $this->addFields( $value );
208
209 return true;
210 }
211
212 return false;
213 }
214
215 /**
216 * Add a set of WHERE clauses to the internal array.
217 * Clauses can be formatted as 'foo=bar' or array('foo' => 'bar'),
218 * the latter only works if the value is a constant (i.e. not another field)
219 *
220 * If $value is an empty array, this function does nothing.
221 *
222 * For example, array('foo=bar', 'baz' => 3, 'bla' => 'foo') translates
223 * to "foo=bar AND baz='3' AND bla='foo'"
224 * @param string|array $value
225 */
226 protected function addWhere( $value ) {
227 if ( is_array( $value ) ) {
228 // Sanity check: don't insert empty arrays,
229 // Database::makeList() chokes on them
230 if ( count( $value ) ) {
231 $this->where = array_merge( $this->where, $value );
232 }
233 } else {
234 $this->where[] = $value;
235 }
236 }
237
238 /**
239 * Same as addWhere(), but add the WHERE clauses only if a condition is met
240 * @param string|array $value
241 * @param bool $condition If false, do nothing
242 * @return bool $condition
243 */
244 protected function addWhereIf( $value, $condition ) {
245 if ( $condition ) {
246 $this->addWhere( $value );
247
248 return true;
249 }
250
251 return false;
252 }
253
254 /**
255 * Equivalent to addWhere(array($field => $value))
256 * @param string $field Field name
257 * @param string $value Value; ignored if null or empty array;
258 */
259 protected function addWhereFld( $field, $value ) {
260 // Use count() to its full documented capabilities to simultaneously
261 // test for null, empty array or empty countable object
262 if ( count( $value ) ) {
263 $this->where[$field] = $value;
264 }
265 }
266
267 /**
268 * Add a WHERE clause corresponding to a range, and an ORDER BY
269 * clause to sort in the right direction
270 * @param string $field Field name
271 * @param string $dir If 'newer', sort in ascending order, otherwise
272 * sort in descending order
273 * @param string $start Value to start the list at. If $dir == 'newer'
274 * this is the lower boundary, otherwise it's the upper boundary
275 * @param string $end Value to end the list at. If $dir == 'newer' this
276 * is the upper boundary, otherwise it's the lower boundary
277 * @param bool $sort If false, don't add an ORDER BY clause
278 */
279 protected function addWhereRange( $field, $dir, $start, $end, $sort = true ) {
280 $isDirNewer = ( $dir === 'newer' );
281 $after = ( $isDirNewer ? '>=' : '<=' );
282 $before = ( $isDirNewer ? '<=' : '>=' );
283 $db = $this->getDB();
284
285 if ( !is_null( $start ) ) {
286 $this->addWhere( $field . $after . $db->addQuotes( $start ) );
287 }
288
289 if ( !is_null( $end ) ) {
290 $this->addWhere( $field . $before . $db->addQuotes( $end ) );
291 }
292
293 if ( $sort ) {
294 $order = $field . ( $isDirNewer ? '' : ' DESC' );
295 // Append ORDER BY
296 $optionOrderBy = isset( $this->options['ORDER BY'] )
297 ? (array)$this->options['ORDER BY']
298 : array();
299 $optionOrderBy[] = $order;
300 $this->addOption( 'ORDER BY', $optionOrderBy );
301 }
302 }
303
304 /**
305 * Add a WHERE clause corresponding to a range, similar to addWhereRange,
306 * but converts $start and $end to database timestamps.
307 * @see addWhereRange
308 * @param string $field
309 * @param string $dir
310 * @param string $start
311 * @param string $end
312 * @param bool $sort
313 */
314 protected function addTimestampWhereRange( $field, $dir, $start, $end, $sort = true ) {
315 $db = $this->getDb();
316 $this->addWhereRange( $field, $dir,
317 $db->timestampOrNull( $start ), $db->timestampOrNull( $end ), $sort );
318 }
319
320 /**
321 * Add an option such as LIMIT or USE INDEX. If an option was set
322 * before, the old value will be overwritten
323 * @param string $name Option name
324 * @param string $value Option value
325 */
326 protected function addOption( $name, $value = null ) {
327 if ( is_null( $value ) ) {
328 $this->options[] = $name;
329 } else {
330 $this->options[$name] = $value;
331 }
332 }
333
334 /**
335 * Execute a SELECT query based on the values in the internal arrays
336 * @param string $method Function the query should be attributed to.
337 * You should usually use __METHOD__ here
338 * @param array $extraQuery Query data to add but not store in the object
339 * Format is array(
340 * 'tables' => ...,
341 * 'fields' => ...,
342 * 'where' => ...,
343 * 'options' => ...,
344 * 'join_conds' => ...
345 * )
346 * @return ResultWrapper
347 */
348 protected function select( $method, $extraQuery = array() ) {
349
350 $tables = array_merge(
351 $this->tables,
352 isset( $extraQuery['tables'] ) ? (array)$extraQuery['tables'] : array()
353 );
354 $fields = array_merge(
355 $this->fields,
356 isset( $extraQuery['fields'] ) ? (array)$extraQuery['fields'] : array()
357 );
358 $where = array_merge(
359 $this->where,
360 isset( $extraQuery['where'] ) ? (array)$extraQuery['where'] : array()
361 );
362 $options = array_merge(
363 $this->options,
364 isset( $extraQuery['options'] ) ? (array)$extraQuery['options'] : array()
365 );
366 $join_conds = array_merge(
367 $this->join_conds,
368 isset( $extraQuery['join_conds'] ) ? (array)$extraQuery['join_conds'] : array()
369 );
370
371 // getDB has its own profileDBIn/Out calls
372 $db = $this->getDB();
373
374 $this->profileDBIn();
375 $res = $db->select( $tables, $fields, $where, $method, $options, $join_conds );
376 $this->profileDBOut();
377
378 return $res;
379 }
380
381 /**
382 * @param string $query
383 * @param string $protocol
384 * @return null|string
385 */
386 public function prepareUrlQuerySearchString( $query = null, $protocol = null ) {
387 $db = $this->getDb();
388 if ( !is_null( $query ) || $query != '' ) {
389 if ( is_null( $protocol ) ) {
390 $protocol = 'http://';
391 }
392
393 $likeQuery = LinkFilter::makeLikeArray( $query, $protocol );
394 if ( !$likeQuery ) {
395 $this->dieUsage( 'Invalid query', 'bad_query' );
396 }
397
398 $likeQuery = LinkFilter::keepOneWildcard( $likeQuery );
399
400 return 'el_index ' . $db->buildLike( $likeQuery );
401 } elseif ( !is_null( $protocol ) ) {
402 return 'el_index ' . $db->buildLike( "$protocol", $db->anyString() );
403 }
404
405 return null;
406 }
407
408 /**
409 * Filters hidden users (where the user doesn't have the right to view them)
410 * Also adds relevant block information
411 *
412 * @param bool $showBlockInfo
413 * @return void
414 */
415 public function showHiddenUsersAddBlockInfo( $showBlockInfo ) {
416 $this->addTables( 'ipblocks' );
417 $this->addJoinConds( array(
418 'ipblocks' => array( 'LEFT JOIN', 'ipb_user=user_id' ),
419 ) );
420
421 $this->addFields( 'ipb_deleted' );
422
423 if ( $showBlockInfo ) {
424 $this->addFields( array( 'ipb_id', 'ipb_by', 'ipb_by_text', 'ipb_reason', 'ipb_expiry', 'ipb_timestamp' ) );
425 }
426
427 // Don't show hidden names
428 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
429 $this->addWhere( 'ipb_deleted = 0 OR ipb_deleted IS NULL' );
430 }
431 }
432
433 /**@}*/
434
435 /************************************************************************//**
436 * @name Utility methods
437 * @{
438 */
439
440 /**
441 * Add information (title and namespace) about a Title object to a
442 * result array
443 * @param array $arr Result array à la ApiResult
444 * @param Title $title
445 * @param string $prefix Module prefix
446 */
447 public static function addTitleInfo( &$arr, $title, $prefix = '' ) {
448 $arr[$prefix . 'ns'] = intval( $title->getNamespace() );
449 $arr[$prefix . 'title'] = $title->getPrefixedText();
450 }
451
452 /**
453 * Add a sub-element under the page element with the given page ID
454 * @param int $pageId Page ID
455 * @param array $data Data array à la ApiResult
456 * @return bool Whether the element fit in the result
457 */
458 protected function addPageSubItems( $pageId, $data ) {
459 $result = $this->getResult();
460 $result->setIndexedTagName( $data, $this->getModulePrefix() );
461
462 return $result->addValue( array( 'query', 'pages', intval( $pageId ) ),
463 $this->getModuleName(),
464 $data );
465 }
466
467 /**
468 * Same as addPageSubItems(), but one element of $data at a time
469 * @param int $pageId Page ID
470 * @param array $item Data array à la ApiResult
471 * @param string $elemname XML element name. If null, getModuleName()
472 * is used
473 * @return bool Whether the element fit in the result
474 */
475 protected function addPageSubItem( $pageId, $item, $elemname = null ) {
476 if ( is_null( $elemname ) ) {
477 $elemname = $this->getModulePrefix();
478 }
479 $result = $this->getResult();
480 $fit = $result->addValue( array( 'query', 'pages', $pageId,
481 $this->getModuleName() ), null, $item );
482 if ( !$fit ) {
483 return false;
484 }
485 $result->setIndexedTagName_internal( array( 'query', 'pages', $pageId,
486 $this->getModuleName() ), $elemname );
487
488 return true;
489 }
490
491 /**
492 * Set a query-continue value
493 * @param string $paramName Parameter name
494 * @param string|array $paramValue Parameter value
495 */
496 protected function setContinueEnumParameter( $paramName, $paramValue ) {
497 $this->getResult()->setContinueParam( $this, $paramName, $paramValue );
498 }
499
500 /**
501 * Convert an input title or title prefix into a dbkey.
502 *
503 * $namespace should always be specified in order to handle per-namespace
504 * capitalization settings.
505 *
506 * @param string $titlePart Title part
507 * @param int $defaultNamespace Namespace of the title
508 * @return string DBkey (no namespace prefix)
509 */
510 public function titlePartToKey( $titlePart, $namespace = NS_MAIN ) {
511 $t = Title::makeTitleSafe( $namespace, $titlePart . 'x' );
512 if ( !$t ) {
513 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
514 }
515 if ( $namespace != $t->getNamespace() || $t->isExternal() ) {
516 // This can happen in two cases. First, if you call titlePartToKey with a title part
517 // that looks like a namespace, but with $defaultNamespace = NS_MAIN. It would be very
518 // difficult to handle such a case. Such cases cannot exist and are therefore treated
519 // as invalid user input. The second case is when somebody specifies a title interwiki
520 // prefix.
521 $this->dieUsageMsg( array( 'invalidtitle', $titlePart ) );
522 }
523
524 return substr( $t->getDbKey(), 0, -1 );
525 }
526
527 /**
528 * Gets the personalised direction parameter description
529 *
530 * @param string $p ModulePrefix
531 * @param string $extraDirText Any extra text to be appended on the description
532 * @return array
533 */
534 public function getDirectionDescription( $p = '', $extraDirText = '' ) {
535 return array(
536 "In which direction to enumerate{$extraDirText}",
537 " newer - List oldest first. Note: {$p}start has to be before {$p}end.",
538 " older - List newest first (default). Note: {$p}start has to be later than {$p}end.",
539 );
540 }
541
542 /**
543 * @param string $hash
544 * @return bool
545 */
546 public function validateSha1Hash( $hash ) {
547 return preg_match( '/^[a-f0-9]{40}$/', $hash );
548 }
549
550 /**
551 * @param string $hash
552 * @return bool
553 */
554 public function validateSha1Base36Hash( $hash ) {
555 return preg_match( '/^[a-z0-9]{31}$/', $hash );
556 }
557
558 /**
559 * Check whether the current user has permission to view revision-deleted
560 * fields.
561 * @return bool
562 */
563 public function userCanSeeRevDel() {
564 return $this->getUser()->isAllowedAny(
565 'deletedhistory',
566 'deletedtext',
567 'suppressrevision',
568 'viewsuppressed'
569 );
570 }
571
572 /**@}*/
573
574 /************************************************************************//**
575 * @name Deprecated
576 * @{
577 */
578
579 /**
580 * Estimate the row count for the SELECT query that would be run if we
581 * called select() right now, and check if it's acceptable.
582 * @deprecated since 1.24
583 * @return bool True if acceptable, false otherwise
584 */
585 protected function checkRowCount() {
586 wfDeprecated( __METHOD__, '1.24' );
587 $db = $this->getDB();
588 $this->profileDBIn();
589 $rowcount = $db->estimateRowCount(
590 $this->tables,
591 $this->fields,
592 $this->where,
593 __METHOD__,
594 $this->options
595 );
596 $this->profileDBOut();
597
598 if ( $rowcount > $this->getConfig()->get( 'APIMaxDBRows' ) ) {
599 return false;
600 }
601
602 return true;
603 }
604
605 /**
606 * Convert a title to a DB key
607 * @deprecated since 1.24, past uses of this were always incorrect and should
608 * have used self::titlePartToKey() instead
609 * @param string $title Page title with spaces
610 * @return string Page title with underscores
611 */
612 public function titleToKey( $title ) {
613 wfDeprecated( __METHOD__, '1.24' );
614 // Don't throw an error if we got an empty string
615 if ( trim( $title ) == '' ) {
616 return '';
617 }
618 $t = Title::newFromText( $title );
619 if ( !$t ) {
620 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
621 }
622
623 return $t->getPrefixedDBkey();
624 }
625
626 /**
627 * The inverse of titleToKey()
628 * @deprecated since 1.24, unused and probably never needed
629 * @param string $key Page title with underscores
630 * @return string Page title with spaces
631 */
632 public function keyToTitle( $key ) {
633 wfDeprecated( __METHOD__, '1.24' );
634 // Don't throw an error if we got an empty string
635 if ( trim( $key ) == '' ) {
636 return '';
637 }
638 $t = Title::newFromDBkey( $key );
639 // This really shouldn't happen but we gotta check anyway
640 if ( !$t ) {
641 $this->dieUsageMsg( array( 'invalidtitle', $key ) );
642 }
643
644 return $t->getPrefixedText();
645 }
646
647 /**
648 * Inverse of titlePartToKey()
649 * @deprecated since 1.24, unused and probably never needed
650 * @param string $keyPart DBkey, with prefix
651 * @return string Key part with underscores
652 */
653 public function keyPartToTitle( $keyPart ) {
654 wfDeprecated( __METHOD__, '1.24' );
655 return substr( $this->keyToTitle( $keyPart . 'x' ), 0, -1 );
656 }
657
658 /**@}*/
659 }
660
661 /**
662 * @ingroup API
663 */
664 abstract class ApiQueryGeneratorBase extends ApiQueryBase {
665
666 private $mGeneratorPageSet = null;
667
668 /**
669 * Switch this module to generator mode. By default, generator mode is
670 * switched off and the module acts like a normal query module.
671 * @since 1.21 requires pageset parameter
672 * @param ApiPageSet $generatorPageSet ApiPageSet object that the module will get
673 * by calling getPageSet() when in generator mode.
674 */
675 public function setGeneratorMode( ApiPageSet $generatorPageSet ) {
676 if ( $generatorPageSet === null ) {
677 ApiBase::dieDebug( __METHOD__, 'Required parameter missing - $generatorPageSet' );
678 }
679 $this->mGeneratorPageSet = $generatorPageSet;
680 }
681
682 /**
683 * Get the PageSet object to work on.
684 * If this module is generator, the pageSet object is different from other module's
685 * @return ApiPageSet
686 */
687 protected function getPageSet() {
688 if ( $this->mGeneratorPageSet !== null ) {
689 return $this->mGeneratorPageSet;
690 }
691
692 return parent::getPageSet();
693 }
694
695 /**
696 * Overrides ApiBase to prepend 'g' to every generator parameter
697 * @param string $paramName Parameter name
698 * @return string Prefixed parameter name
699 */
700 public function encodeParamName( $paramName ) {
701 if ( $this->mGeneratorPageSet !== null ) {
702 return 'g' . parent::encodeParamName( $paramName );
703 } else {
704 return parent::encodeParamName( $paramName );
705 }
706 }
707
708 /**
709 * Overridden to set the generator param if in generator mode
710 * @param string $paramName Parameter name
711 * @param string|array $paramValue Parameter value
712 */
713 protected function setContinueEnumParameter( $paramName, $paramValue ) {
714 if ( $this->mGeneratorPageSet !== null ) {
715 $this->getResult()->setGeneratorContinueParam( $this, $paramName, $paramValue );
716 } else {
717 parent::setContinueEnumParameter( $paramName, $paramValue );
718 }
719 }
720
721 /**
722 * @see ApiBase::getHelpFlags()
723 *
724 * Corresponding messages: api-help-flag-generator
725 */
726 protected function getHelpFlags() {
727 $flags = parent::getHelpFlags();
728 $flags[] = 'generator';
729 return $flags;
730 }
731
732 /**
733 * Execute this module as a generator
734 * @param ApiPageSet $resultPageSet All output should be appended to this object
735 */
736 abstract public function executeGenerator( $resultPageSet );
737 }